﻿using MX.Core.Log;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace UserCenter.Api.Tools
{
    public class ErrorCodeHelper
    {
        static ILogger logger = Logger.GetLogger("ErrorCode");
        static Dictionary<int, string> maps = new Dictionary<int, string>();

        static string codeBase = Assembly.GetCallingAssembly().CodeBase;


        static ErrorCodeHelper()
        {
            string errPath = Path.Combine(Path.GetDirectoryName(new Uri(codeBase).LocalPath), "err.json");
            if (!File.Exists(errPath))
            {
                logger.Warn($"错误代码配置文件不存在\n{errPath}");
                throw new FileNotFoundException($"文件路径不存在{errPath}");
            }
            else
            {
                try
                {
                    JObject jsonDefine = JsonConvert.DeserializeObject(File.ReadAllText(errPath, Encoding.UTF8)) as JObject;
                    var properties = jsonDefine.Properties();
                    foreach (var property in properties)
                    {
                        int layer = int.Parse(property.Name);
                        var codeDicts = (property.Value as JArray);
                        foreach (JArray item in codeDicts)
                        {

                            int code = layer + int.Parse(item.First.ToObject<string>());
                            string message = item.Last.ToObject<string>();
                            maps[code] = message;
                        }
                    }
                }
                catch (Exception ex)
                {
                    logger.Error(ex, "");
                    throw ex;
                }
            }
        }

        static public string Get(int code)
        {
            return maps[code];
        }

    }
}
